import React, { lazy, Suspense } from 'react'
import { Spin } from 'antd'
import { NonIndexRouteObject } from 'react-router-dom'
import { routes } from '@/router'
import type { RouterRes } from '@/service/login/types'

export interface IRouteObject extends Omit<NonIndexRouteObject, 'children'> {
	name?: string
	meta?: { title: string }
	hidden?: boolean
	children?: IRouteObject[]
}

// 映射用户菜单生成个路由表
const modules = import.meta.glob<any>('/src/views/**/*.tsx')

export function mapRouters(userMenus: RouterRes[]): IRouteObject[] {
	const routes: IRouteObject[] = []

	function _recurseGetRoute(menus: RouterRes[]) {
		for (const menu of menus) {
			if (!menu.children) {
				const route: IRouteObject = {
					name: menu.name,
					path: menu.path,
					meta: { title: menu.meta.title },
					hidden: menu.hidden,
					element: lazyLoad(lazy(modules['/src/views' + menu.component + '.tsx']))
				}
				routes.push(route)
			} else {
				_recurseGetRoute(menu.children)
			}
		}
	}
	_recurseGetRoute(userMenus)

	return routes
}

// 懒加载路由模块
export const lazyLoad = (
	Comp: React.LazyExoticComponent<React.MemoExoticComponent<() => JSX.Element>>
) => {
	return (
		<Suspense
			fallback={
				<Spin
					size="large"
					style={{
						display: 'flex',
						alignItems: 'center',
						justifyContent: 'center',
						height: '100%'
					}}
				/>
			}
		>
			<Comp />
		</Suspense>
	)
}

// 向目标路由中的children增加路由
export const addRouter = (name: string, addRoutes: IRouteObject[]) => {
	const target = routes.find((item) => item.name === name)

	if (target) {
		// 遍历children中是否已存在，防止重复添加
		const newRoutes = addRoutes.filter((route) =>
			target.children?.find((item) => route.path !== item.path)
		)
		if (newRoutes.length) target?.children?.push(...newRoutes)
	}
}
